package demo;

import org.neo4j.driver.*;
import org.neo4j.driver.types.Node;
import org.neo4j.driver.types.Path;
import org.neo4j.driver.types.Relationship;

import java.util.Iterator;

public class Neo4jDemo {
    public static void main(String[] args) {
        try  {
            Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "198234bh"));
            Session session = driver.session();

            // 执行 Cypher 查询
            String cypherQuery = "MATCH p=()-->() RETURN p ";
//            String cypherQuery = "MATCH (n:NorthDistrictPolygon) RETURN n";

            Result result = session.run(cypherQuery);


            // 处理查询结果
            while (result.hasNext()) {
                Record record = result.next();

                // 获取节点数据
                Value value = record.get("p");
//                Value value = record.get("p");


                Path path = value.asPath();

                // 获取路径中的节点
                Iterable<Node> nodes = path.nodes();

            // 获取路径中的关系
                Iterable<Relationship> relationships = path.relationships();

            // 创建一个字符串来存储路径的描述
                StringBuilder pathDescription = new StringBuilder();

            // 遍历节点和关系
                Iterator<Node> nodeIterator = nodes.iterator();
                Iterator<Relationship> relationshipIterator = relationships.iterator();

            // 添加第一个节点
                if (nodeIterator.hasNext()) {
                    Node firstNode = nodeIterator.next();
                    String firstNodeName = firstNode.get("feature").asString();
                    pathDescription.append("(");
                    pathDescription.append(firstNodeName);
                    pathDescription.append(")");
                }

            // 遍历关系并添加节点和关系
                while (relationshipIterator.hasNext()) {
                    Relationship relationship = relationshipIterator.next();
                    String relationshipType = relationship.type();
                    pathDescription.append("-[");
                    pathDescription.append(relationshipType);
                    pathDescription.append("]->");

                    // 添加下一个节点
                    if (nodeIterator.hasNext()) {
                        Node nextNode = nodeIterator.next();
                        String nextNodeName = nextNode.get("name").asString();
                        pathDescription.append("(");
                        pathDescription.append(nextNodeName);
                        pathDescription.append(")");
                    }
                }

                System.out.println("Path: " + pathDescription.toString());

            }
        } catch (Exception e) {

        }
    }
}

